package http;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import java.net.URLEncoder;

import com.alibaba.fastjson.JSON;

import model.RestResponse;
import model.character.RestCustomer;
import model.character.RestUser;
import model.character.RestUserAddress;
import model.dictionary.RestCity;
import model.dictionary.RestPhoto;
import model.order.RestOrder;
import model.order.RestOrderCar;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.omg.CORBA.NameValuePair;

/**
 * Created by Administrator on 2015/12/16.
 */
public class ClientPost {
    public static void main(String[] args) throws Exception {
//        sendPost();
//        post();
        get();
    }

    public static String sendPost() {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
//            cft-vote.ihengtian.top
            String url ="http://cft-vote.ihengtian.top/wechat.do?signature=123&timestamp=23424&nonce=3242z&echostr=23432";

//            String param = "order="+JSON.toJSONString(restOrder);

//            String param = "order="+"{\"address\":\"上海市陆家嘴地铁2号线\",\"appointment\":1457955600000,\"city\":{\"cityCarParts\":[{\"carPart\":{\"id\":1,\"partname\":\"前挡风\",\"price\":50.00},\"carPartPrice\":50.00,\"id\":1},{\"carPart\":{\"id\":2,\"partname\":\"后挡风\",\"price\":50.00},\"carPartPrice\":50.00,\"id\":2},{\"carPart\":{\"id\":3,\"partname\":\"左前\",\"price\":50.00},\"carPartPrice\":50.00,\"id\":3},{\"carPart\":{\"id\":4,\"partname\":\"左后\",\"price\":50.00},\"carPartPrice\":50.00,\"id\":4},{\"carPart\":{\"id\":5,\"partname\":\"右前\",\"price\":50.00},\"carPartPrice\":50.00,\"id\":5},{\"carPart\":{\"id\":6,\"partname\":\"右后\",\"price\":50.00},\"carPartPrice\":50.00,\"id\":6}],\"code\":\"289\",\"id\":1,\"name\":\"上海\"},\"createDate\":1457869249058,\"customer\":{\"user\":{\"name\":\"13636572175\"}},\"finalprice\":300.00,\"lat\":31.201002,\"lgt\":121.63427,\"orderCars\":[{\"callPrice\":300.00,\"carModel\":{\"carSery\":{\"carBrand\":{\"brandName\":\"奥迪\",\"id\":1,\"logoUrl\":\"sdfldfsg;kjdjaslk;gfdjk\",\"photo\":{\"createDate\":1457166719000,\"enable\":1,\"id\":58,\"type\":\"img\",\"url\":\"/photo/58/aodi.jpg\"}},\"id\":1,\"seryName\":\"奥迪 奥迪A1(进口)\"},\"id\":1,\"name\":\"奥迪 奥迪A1(进口)\"},\"orderCityCarParts\":[{\"cityCarPart\":{\"carPart\":{\"id\":1,\"partname\":\"前挡风\",\"price\":50.00},\"id\":1}},{\"cityCarPart\":{\"carPart\":{\"id\":2,\"partname\":\"后挡风\",\"price\":50.00},\"id\":2}},{\"cityCarPart\":{\"carPart\":{\"id\":3,\"partname\":\"左前\",\"price\":50.00},\"id\":3}},{\"cityCarPart\":{\"carPart\":{\"id\":4,\"partname\":\"左后\",\"price\":50.00},\"id\":4}},{\"cityCarPart\":{\"carPart\":{\"id\":5,\"partname\":\"右前\",\"price\":50.00},\"id\":5}},{\"cityCarPart\":{\"carPart\":{\"id\":6,\"partname\":\"右后\",\"price\":50.00},\"id\":6}}],\"priority\":1,\"realPrice\":300.00}],\"orignprice\":300.00,\"products\":[{\"photos\":[],\"product\":{\"id\":1,\"photos\":[]}}],\"remark\":\"带你上天\",\"type\":0,\"userAddress\":{\"address\":\"上海市陆家嘴地铁2号线\",\"addressMobile\":\"13636572175\",\"addressName\":\"高帅\",\"id\":7,\"lat\":31.2436,\"lgt\":121.509,\"user\":{\"address\":\"中国上海市长宁区汇川路113号\",\"age\":0,\"id\":2,\"lat\":31.218,\"lgt\":121.418,\"mobile\":\"13636572175\",\"name\":\"13636572175\",\"nickname\":\"高帅逗逼\"}}}\n";

            String param = "<xml>\n" +
                    " <ToUserName><![CDATA[toUser]]></ToUserName>\n" +
                    " <FromUserName><![CDATA[fromUser]]></FromUserName>\n" +
                    " <CreateTime>1348831860</CreateTime>\n" +
                    " <MsgType><![CDATA[text]]></MsgType>\n" +
                    " <Content><![CDATA[this is a test]]></Content>\n" +
                    " <MsgId>1234567890123456</MsgId>\n" +
                    " </xml>";

            System.out.println(param);

            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

            System.out.println(result);
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

    public static void post() throws IOException {
        HttpClient client = new HttpClient();

//        RestUserAddress restUserAddress = new RestUserAddress();
//        restUserAddress.setAddress("sdfadf");
//        restUserAddress.setLat(Float.valueOf("12"));
//        restUserAddress.setLgt(Float.valueOf("12"));
//        restUserAddress.setAddressName("ssfa");
//        restUserAddress.setAddressMobile("sdfsdfs");

        String url ="http://localhost:8999/api/rest/worker/update/inspect/13636572175";

        PostMethod method = new PostMethod(url);

        method.addRequestHeader("Content-Type","application/json");


//        method.addParameter("order",JSON.toJSONString(restOrder));
        method.addParameter("cityCode","289");
        method.addParameter("inspect","");

        HttpMethodParams param = method.getParams();
        param.setContentCharset("UTF-8");

        client.executeMethod(method);
        //打印服务器返回的状态
        System.out.println(method.getStatusLine());
        //打印返回的信息
        InputStream stream = method.getResponseBodyAsStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        StringBuffer buf = new StringBuffer();
        String line;
        while (null != (line = br.readLine())) {
            buf.append(line).append("\n");
        }
        System.out.println(buf.toString());
        //释放连接
        method.releaseConnection();
    }

    public static void get() throws Exception {
        HttpClient client = new HttpClient();
//        GetMethod method = new GetMethod("http://minis.inmycars.com/api/rest/activity/competitor/1/vote");
//        GetMethod method = new GetMethod("http://localhost:8999/api/rest/order/worker/confirm/13636572175?orderId=46");
//        GetMethod method = new GetMethod("http://localhost:8999/api/rest/order/customer/confirm/46?mobile=13636572175");
        GetMethod method = new GetMethod("http://localhost:8999/api/rest/socket/insert/data?result=fdsafafhgagsdfsafadd");
//        GetMethod method = new GetMethod("http://cft-vote.ihengtian.top/api/rest/car/brands/alpha");
//        GetMethod method = new GetMethod("http://localhost:8999/api/rest/order/worker/update/13636572175?orderId=46");

        client.executeMethod(method);
        //打印服务器返回的状态
        System.out.println(method.getStatusLine());
        //打印返回的信息
        System.out.println();
        InputStream stream = method.getResponseBodyAsStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        StringBuffer buf = new StringBuffer();
        String line;
        while (null != (line = br.readLine())) {
            buf.append(line).append("\n");
        }
        System.out.println(buf.toString());
        RestResponse restResponse = JSON.parseObject(buf.toString(),RestResponse.class);
        String result = restResponse.getData().toString();
        System.out.println(result);
        System.out.println(ByteAndHex.bytesToHexString(result.getBytes()));

        System.out.println(buf.toString());
        //释放连接
        method.releaseConnection();
    }


}
